// 云函数入口文件
const cloud = require('wx-server-sdk')
// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // console.log(event);return;
    var bookId=event.bookId;
    // var bookId;return;
    //获取音频文件地址，放到数组中
    var audioPathArr = [];
    var audioList = db.collection("audio").where({
      bookId:bookId
    }).get()
    .then(res => {
      // console.log(res);return;
      // console.log(res.data);return;
      res.data.forEach((item,index)=>{
        audioPathArr.push(item.audioPath)
      })

      //删除音频文件和数据记录
      cloud.deleteFile({
        fileList: audioPathArr,
        success: res => {
          console.log(res)
        },
        fail: console.error
      })

      db.collection("audio").where({
        bookId:bookId
      }).remove()
    })
    .catch(err => {
      console.lot(err)
    })

    // console.log(audioPathArr,"audioPathArr");
      //删除音频文件


    //获取图书图片地址
    db.collection("book").doc(bookId).get()
    .then(res=>{

      //获取图片地址
      var fileids=res.data.fileids;
      // console.log(fileids,"fileids")
      console.log(bookId,"--here--");return
      //删除图片和图书记录
      cloud.deleteFile({
        fileList: fileids,
        success: res => {
          //删除图书记录
          // console.log(bookId,"bookId");
          db.collection("book").doc(bookId).remove()
          .then(res=>{
            console.log(res)
            // return res;
          })
          .catch(err=>{
            console.log()
          })

        },
        fail: console.error
      })

    })
    .catch(err=>{
      console.log(err)
    })

      //获取
    // return;
    // return audioList
    // console.log(audioList);return;



  } catch (e) {
    console.error(e)
  }
}